﻿using System;
using System.Linq;
using MySql.Data.MySqlClient;
using System.Data;
using iRealtor.Maps.DataAccess.Models;

namespace iRealtor.Maps.DataAccess.Dao.EntityDataProviders
{
	public class PlaceImagesDataProvider : EntityDataProvider<PlaceImage>
	{
		private const string INSERT_COMMAND = "INSERT INTO PlaceImages(PlaceId, Path, ThumbPath, IsMain) VALUES(@PlaceId, @Path, @ThumbPath, @IsMain); SELECT @@IDENTITY;";
		private const string UPDATE_COMMAND = "UPDATE Places SET PlaceId=@PlaceId, Path=@Path, ThumbPath=@ThumbPath, IsMain=@IsMain  WHERE ImageId=@ImageId;";
		private const string SELECT_COMMAND = "SELECT * FROM PlaceImages WHERE ImageId=@ImageId;";

		public override void Save(PlaceImage entity, IMySqlCommandCreater cmdCreater)
		{
			MySqlCommand cmd = cmdCreater.CreateCommand();

			if (entity.ImageId == 0)
			{
				cmd.CommandText = INSERT_COMMAND;
			}
			else
			{
				cmd.CommandText = UPDATE_COMMAND;
				cmd.Parameters.Add("@ImageId", MySqlDbType.Int32).Value = entity.ImageId;
			}

			cmd.Parameters.Add("@PlaceId", MySqlDbType.Int32).Value = entity.PlaceId;
			cmd.Parameters.Add("@Path", MySqlDbType.String).Value = entity.Path;
			cmd.Parameters.Add("@ThumbPath", MySqlDbType.String).Value = entity.ThumbPath;
			cmd.Parameters.Add("@IsMain", MySqlDbType.Bit).Value = entity.IsMain;

			if (entity.ImageId == 0)
			{
				entity.ImageId = Convert.ToInt32(cmd.ExecuteScalar());
			}
			else
			{
				if (cmd.ExecuteNonQuery() == 0)
				{
					throw new Exception(string.Format("Place image({0}) was not found in database.", entity.ImageId));
				}
			}
		}

		public override PlaceImage Load(object key, IMySqlCommandCreater cmdCreater)
		{
			MySqlCommand cmd = cmdCreater.CreateCommand(SELECT_COMMAND);
			cmd.Parameters.Add("@ImageId", MySqlDbType.Int32).Value = key;

			return Load(cmd).FirstOrDefault();
		}

		public override PlaceImage Load(DataRow row)
		{
			var image = new PlaceImage();

			if (!(row["ImageId"] is DBNull))
				image.ImageId = Convert.ToInt32(row["ImageId"]);
			if (!(row["PlaceId"] is DBNull))
				image.PlaceId = Convert.ToInt32(row["PlaceId"]);
			if (!(row["Path"] is DBNull))
				image.Path = Convert.ToString(row["Path"]);
			if (!(row["ThumbPath"] is DBNull))
				image.ThumbPath = Convert.ToString(row["ThumbPath"]);
			if (!(row["IsMain"] is DBNull))
				image.IsMain = Convert.ToBoolean(row["IsMain"]);

			return image;
		}
	}
}
